﻿#region --- License & Copyright Notice
/*
CRUD Services Library

Copyright 2012 Jeevan James

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;

namespace CrudServices
{
    /// <summary>
    /// Provides a strongly-typed wrapper for the client portion of the CRUD service. The class's
    /// constructor accepts an instance of the weakly-typed concrete CRUD client class, and provides
    /// the wrappers to convert the weakly-typed functionality to strongly-typed.
    /// </summary>
    public sealed class CrudClient
    {
        private readonly ICrudService _client;

        public CrudClient(ICrudService client)
        {
            if (client == null)
                throw new ArgumentNullException("client");
            _client = client;
        }

        public IEnumerable<TEntity> Search<TEntity>(SearchCriteria criteria = null)
        {
            string json = _client.Search(criteria ?? SearchCriteriaBuilder.From<TEntity>().SelectAll());
            return Deserialize<IEnumerable<TEntity>>(json);
        }

        public TEntity Find<TEntity>(int id)
        {
            string json = _client.Find(typeof(TEntity).Name, id);
            return Deserialize<TEntity>(json);
        }

        public TEntity Add<TEntity>(TEntity entity)
        {
            var entityArray = new[] { entity };
            string resultJson = _client.Add(typeof(TEntity).Name, Serialize(entityArray));
            var resultEntities = Deserialize<IEnumerable<TEntity>>(resultJson);
            return resultEntities.FirstOrDefault();
        }

        public IEnumerable<TEntity> Add<TEntity>(IEnumerable<TEntity> entities)
        {
            string resultJson = _client.Add(typeof(TEntity).Name, Serialize(entities));
            return Deserialize<IEnumerable<TEntity>>(resultJson);
        }

        public int Update<TEntity>(params TEntity[] entities)
        {
            int rowsAffected = _client.Update(Serialize(entities));
            return rowsAffected;
        }

        public int Delete<TEntity>(params TEntity[] entities)
        {
            int rowsAffected = _client.Delete(Serialize(entities));
            return rowsAffected;
        }

        public int Delete<TEntity>(params int[] entityIds)
        {
            return _client.DeleteIds(typeof(TEntity).Name, entityIds);
        }

        private static string Serialize<TValue>(TValue value)
        {
            var serializer = new DataContractJsonSerializer(typeof(TValue));
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, value);
                byte[] array = stream.ToArray();
                return Encoding.UTF8.GetString(array, 0, array.Length);
            }
        }

        private static TResult Deserialize<TResult>(string json)
        {
            var deserializer = new DataContractJsonSerializer(typeof(TResult));
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                return (TResult)deserializer.ReadObject(stream);
        }
    }
}